import os
import hashlib
import sqlite3
from datetime import datetime
import argparse

def calculate_file_hash(file_path):
    """计算文件的SHA256哈希值"""
    hasher = hashlib.sha256()
    with open(file_path, 'rb') as f:
        buf = f.read()
        hasher.update(buf)
    return hasher.hexdigest()

def check_files_and_update_db(db_conn, base_dir):
    """遍历file_merge表并检查文件"""
    cursor = db_conn.cursor()
    cursor.execute('SELECT id, file_name, aim_folder, file_hash FROM file_merge WHERE deal_flag=1')
    rows = cursor.fetchall()
    
    for row in rows:
        id, file_name, aim_folder, original_hash = row
        destination_dir = os.path.join(base_dir, aim_folder)
        destination_path = os.path.join(destination_dir, file_name)
        
        # 检查文件是否存在
        if not os.path.exists(destination_path):
            cursor.execute('UPDATE file_merge SET deal_flag=2 WHERE id=?', (id,))
            db_conn.commit()
            print(f'File not found: {destination_path}, setting deal_flag to 2.')
            continue
        
        # 计算文件哈希值
        current_hash = calculate_file_hash(destination_path)
        
        # 如果哈希值不一致
        if current_hash != original_hash:
            cursor.execute('UPDATE file_merge SET deal_flag=3 WHERE id=?', (id,))
            db_conn.commit()
            print(f'Hash mismatch for file: {destination_path}, setting deal_flag to 3.')
            continue
        
        # 所有检查通过，插入video_hash表
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute('''
            INSERT INTO video_hash (file_path, file_name, file_hash, create_time) 
            VALUES (?, ?, ?, ?)
        ''', (os.path.join(aim_folder, file_name), file_name, current_hash, now))
        
        # 更新file_merge表中的deal_flag为9
        cursor.execute('UPDATE file_merge SET deal_flag=9 WHERE id=?', (id,))
        db_conn.commit()
        
        print(f'All checks passed for file: {destination_path}, setting deal_flag to 9.')

if __name__ == '__main__':
    
    parser = argparse.ArgumentParser(description="Scan directory and store file information into the database.")
    parser.add_argument('--db', required=True, help="Directory containing the SQLite database file (file_hash.db)")

    args = parser.parse_args()

    script_dir = args.db
    video_base_dir = args.db

    # # 获取脚本所在目录
    # script_dir = os.path.dirname(os.path.abspath(__file__))
    
    # # 使用脚本所在目录作为基础目录
    # video_base_dir = script_dir  # 直接使用脚本所在目录作为基础目录
    
    # 假设数据库文件位于脚本所在目录下的'E_RelaxArea_video'文件夹中
    db_path = os.path.join(script_dir, 'file_hash.db')

    # 创建/连接数据库
    conn = sqlite3.connect(db_path)

    # 检查文件并更新数据库
    check_files_and_update_db(conn, video_base_dir)

    # 关闭数据库连接
    conn.close()